package com.ruoyi.tb.lmt.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StreamUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.TbWheelDiameter;
import com.ruoyi.tb.lmt.domain.bo.*;
import com.ruoyi.tb.lmt.domain.vo.*;
import com.ruoyi.tb.lmt.mapper.TbWheelDiameterMapper;
import com.ruoyi.tb.lmt.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 检修工作
 *
 * @author ruoyi
 * @date 2023-12-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/lmtrepairWorkdetail")
public class TbLmtrepairWorkdetailController extends BaseController {

    private final ITbLmtrepairWorkdetailService iTbLmtrepairWorkdetailService;

    private final ITbLmtrepairCheckdetailService iTbLmtrepairCheckdetailService;

    @Autowired
    private ITbFdxdetailService iTbFdxdetailService;

    @Autowired
    private ITbFdxService iTbFdxService;

    @Autowired
    private ITbMutualInspectiondetailService iTbMutualInspectiondetailService;

    @Autowired
    private ITbSpecialInspectiondetailService iTbSpecialInspectiondetailService;

    @Autowired
    private ITbLocomotiveService iTbLocomotiveService;

    @Autowired
    private ITbRepairplanlistService iTbRepairplanlistService;

    @Autowired
    private ITbAcceptancedetailService iTbAcceptancedetailService;

    @Autowired
    private ITbMessageNoticeService iTbMessageNoticeService;

    @Autowired
    private ITbPreflightdetailService iTbPreflightdetailService;

    @Autowired
    private ITbLegacyIssuesService iTbLegacyIssuesService;


    @Autowired
    private ITbRepairplanService iTbRepairplanService;

    /**
     * 查询检修工作列表
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:list")
    @GetMapping("/list")
    public TableDataInfo<TbLmtrepairWorkdetailVo> list(TbLmtrepairWorkdetailBo bo, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出检修工作列表
     */
    @Log(title = "检修工作", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbLmtrepairWorkdetailBo bo, HttpServletResponse response) {
        List<TbLmtrepairWorkdetailVo> list = iTbLmtrepairWorkdetailService.queryList(bo);
        ExcelUtil.exportExcel(list, "检修工作", TbLmtrepairWorkdetailVo.class, response);
    }


    /**
     * 通过列表导出检修工作列表
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:exportByQuery")
    @Log(title = "检修工作导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByQuery")
    public void exportByQuery(String id, String workSelect, String lmtType, String lmtNumber, String repairChar, HttpServletResponse response) {
        List<TbLmtrepairWorkdetailVo> list = iTbLmtrepairWorkdetailService.selectWorkHistoryList(id, workSelect, lmtType, lmtNumber, repairChar);
        ExcelUtil.exportExcel(list, "检修工作", TbLmtrepairWorkdetailVo.class, response);
    }


    /**
     * 任务下达导出检修工作列表
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:exportByWorkList")
    @Log(title = "检修工作导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByWorkList")
    public void exportByWorkList(String id, String status, String lmtType, String lmtNumber, String repairChar, HttpServletResponse response) {
        List<TbLmtrepairWorkdetailVo> list = iTbLmtrepairWorkdetailService.selectWorkList(id, status, lmtType, lmtNumber, repairChar);
        ExcelUtil.exportExcel(list, "检修工作", TbLmtrepairWorkdetailVo.class, response);
    }

    /**
     * 获取检修工作详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:query")
    @GetMapping("/{id}")
    public R<TbLmtrepairWorkdetailVo> getInfo(@NotNull(message = "主键不能为空")
                                              @PathVariable Long id) {
        return R.ok(iTbLmtrepairWorkdetailService.queryById(id));
    }

    @GetMapping("/mapInfo/{id}")
    public R<Map<String, Object>> getInfoMap(@NotNull(message = "主键不能为空")
                                             @PathVariable Long id) {
        return R.ok(iTbLmtrepairWorkdetailService.queryMapById(id));
    }

    //工作明细
    @GetMapping("/workInfo/{id}")
    public R<?> getWorkInfo(@NotNull(message = "主键不能为空")
                            @PathVariable Long id) {
        return R.ok(iTbLmtrepairWorkdetailService.selectWorkInfoList(id));
    }

    /**
     * 新增检修工作
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:add")
    @Log(title = "检修工作", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbLmtrepairWorkdetailBo bo) {
        bo.setStatus("未下达");
        return toAjax(iTbLmtrepairWorkdetailService.insertByBo(bo));
    }

    /**
     * 修改检修工作
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:edit")
    @Log(title = "检修工作", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbLmtrepairWorkdetailBo bo) {
        return toAjax(iTbLmtrepairWorkdetailService.updateByBo(bo));
    }

    /**
     * 删除检修工作
     *
     * @param ids 主键串
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:remove")
    @Log(title = "检修工作", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTbLmtrepairWorkdetailService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:start")
    @Log(title = "计划开始", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/start")
    public R<Void> start(@Validated(AddGroup.class) @RequestBody TbRepairplanlistBo bo) {
        bo.setId(bo.getId());
        bo.setStartTime(bo.getStartTime());
        bo.setEndTime(bo.getEndTime());
        iTbRepairplanlistService.updateByBo(bo);
        return toAjax(iTbLmtrepairWorkdetailService.startByBo(bo));
    }


    //点击任务下达左侧大机列表显示右边未下达的任务
    @GetMapping("/list/work")
    public TableDataInfo<TbLmtrepairWorkdetailVo> workList(String id, String status, String workKind, String workCategory, String workName, String workRequire, String workGroup, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectWorkList(id, status, workKind, workCategory, workName, workRequire, workGroup, pageQuery);
    }

    //下达任务
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:update")
    @Log(title = "下达任务", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update")
    public R<?> updateByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            if (bo.getWorkGroupId() == null) {
                return R.fail("当前选中有没有添加检修工队的工作");
            }
        }
        for (TbLmtrepairWorkdetailBo bo : bos) {
            bo.setStatus("未派活");
            bo.setSendDate(new Date());
            LoginUser currentUser = LoginHelper.getLoginUser();
            bo.setSendUser(currentUser.getUsername());
            if (bo.getStartRequireDate() == null) {
                bo.setStartRequireDate(new Date());
            }
            iTbLmtrepairWorkdetailService.updateByBo(bo);
        }
        return R.ok();
    }

    //根据id和传入数据批量修改
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateStart")
    @Log(title = "批量修改", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/updateStart")
    public R<?> updateStartByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            iTbLmtrepairWorkdetailService.updateByBo(bo);
        }
        return R.ok();
    }

    //撤回任务
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateReturn")
    @Log(title = "撤退任务", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/return")
    public R<?> updateReturnByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            bo.setStatus("未下达");
            iTbLmtrepairWorkdetailService.updateByBo(bo);
        }
        return R.ok();
    }

    //队长派活
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateDispatch")
    @Log(title = "队长派活", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/Dispatch")
    public R<?> updateDispatchByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            bo.setStatus("未开始");
            bo.setSendToUserTime(new Date());
            LoginUser currentUser = LoginHelper.getLoginUser();
            bo.setSendToUserName(currentUser.getUsername());
            iTbLmtrepairWorkdetailService.updateByBo(bo);
        }
        return R.ok();
    }


    //工队派活的显示列表
    @GetMapping("/list/workDispatch")
    public TableDataInfo<TbLmtrepairWorkdetailVo> workDispatchList(String id, String status, String workSelect, String lmtType, String lmtNumber, String repairChar, PageQuery pageQuery, String workKind) {
        return iTbLmtrepairWorkdetailService.selectWorkDispatchList(id, status, workSelect, lmtType, lmtNumber, repairChar, workKind, pageQuery);
    }


    @GetMapping("/list/workOverhaul")
    public TableDataInfo<TbLmtrepairWorkdetailVo> workOverhaulList(String id, String status, String workSelect, String lmtType, String lmtNumber, String repairChar, String workCategory, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectWorkOverhaulList(id, status, workSelect, lmtType, lmtNumber, repairChar, workCategory, pageQuery);
    }

    //检修任务中的撤回任务
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateReturnOverhaul")
    @Log(title = "检修任务中的撤回任务", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/returnOverhaul")
    public R<?>  updateReturnOverhaulByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            if (!LoginHelper.getLoginUser().getUsername().equals(bo.getWorkUser())) {
                throw new IllegalArgumentException("请让主修人设置任务未完成");
            }
            bo.setStatus("未派活");
            //bo.setFillData(null);设置JsonStatus为1，草稿状态
            bo.setJsonStatus("1");
            iTbLmtrepairWorkdetailService.updateByBo(bo);
        }
        return R.ok();
    }

    //检修任务中的任务开始
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateStartOverhaul")
    @Log(title = "检修任务中的任务开始", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/startOverhaul")
    public R<?> updateStartOverhaulByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {

            if (!LoginHelper.getLoginUser().getUsername().equals(bo.getWorkUser())) {
                throw new IllegalArgumentException("任务未开始，请等待主修人开始任务");
            }

            bo.setStatus("未完成");
            bo.setFillData("0");
            bo.setStartTime(new Date());
            //设置目标大机状态为检修中
            Long lmtId = iTbLocomotiveService.selectByLmtId(bo.getLmtRepairId());
            TbLocomotiveBo lmtBo = new TbLocomotiveBo();
            lmtBo.setID(lmtId);
            lmtBo.setStatus("检修中");
            iTbLocomotiveService.updateByBo(lmtBo);
            //设置计划明细为检修中
            TbRepairplanlistBo rplBo = new TbRepairplanlistBo();
            rplBo.setId(lmtId);
            rplBo.setStatus("检修中");
            iTbRepairplanlistService.updateByBo(rplBo);
            iTbLmtrepairWorkdetailService.updateByBo(bo);
        }
        return R.ok();
    }

    //单条数据修改
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateWork")
    @Log(title = "作业调整", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/updateWork")
    public R<?> updateWork(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            iTbLmtrepairWorkdetailService.updateWork(bo);
        }
        return R.ok();
    }

    //检修任务中的任务完成
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateEndOverhaul")
    @Log(title = "检修任务中的任务完成", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/endOverhaul")
    public R<?> updateEndOverhaulByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {

            if (LoginHelper.getLoginUser().getUsername().equals(bo.getWorkUser2()) && !LoginHelper.getLoginUser().getUsername().equals(bo.getWorkUser())) {
                throw new IllegalArgumentException("请等待主修人完成任务");
            }

            bo.setStatus("已完成");
            bo.setEndTime(new Date());
            //TODO 想添加申请验收人
            iTbLmtrepairWorkdetailService.updateByBo(bo);


            if (bo.getLegacyIssuesStatus() != null && !bo.getLegacyIssuesStatus().equals(2)) {
                TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
                TbLmtrepairWorkdetailVo list = iTbLmtrepairWorkdetailService.selectWorkInfo(bo.getId());
                messageNoticeBo.setMessageId(bo.getId());
                messageNoticeBo.setMessageTitle(list.getLmtNumber() + "任务申请遗留");
                messageNoticeBo.setMessageName(list.getWorkGroup() + "提交了" + list.getLmtNumber() + "大机的任务遗留申请，请及时处理。");
                messageNoticeBo.setMessageType("遗留申请");
                messageNoticeBo.setLmtType(list.getLmtType());
                messageNoticeBo.setLmtNumber(list.getLmtNumber());
                messageNoticeBo.setWorkGroup(list.getWorkGroup());
                messageNoticeBo.setWorkUser(list.getWorkUser());
                messageNoticeBo.setWorkerTeam(list.getWorkerTeam());
                messageNoticeBo.setStatus("0");
                messageNoticeBo.setWorkGroupId(list.getWorkGroupId());
                messageNoticeBo.setTaskUrl(list.getTaskUrl());
                messageNoticeBo.setWorkTime(new Date());
                //设置通知人工队长
                messageNoticeBo.setRecipient(iTbMessageNoticeService.getCaptain(list.getWorkGroupId()));
                iTbMessageNoticeService.insertByBo(messageNoticeBo);

                TbLegacyIssuesBo legacyIssuesBo = new TbLegacyIssuesBo();
                legacyIssuesBo.setWorkdetailId(bo.getId());
                legacyIssuesBo.setStatus("进行中");
                if (list.getLegacyIssues() != null) {
                    legacyIssuesBo.setLegacyIssues(list.getLegacyIssues());
                }
                if (list.getLegacyIssuesData() != null) {
                    legacyIssuesBo.setLegacyIssuesData(list.getLegacyIssuesData());
                }
                if (list.getLegacyIssuesStatus() != null) {
                    legacyIssuesBo.setLegacyIssuesStatus(list.getLegacyIssuesStatus());
                }
                if (list.getLegacyIssuesRemark() != null) {
                    legacyIssuesBo.setLegacyIssuesRemark(list.getLegacyIssuesRemark());
                }
                if (list.getLegacyIssuesSolution() != null) {
                    legacyIssuesBo.setLegacyIssuesSolution(list.getLegacyIssuesSolution());
                }
                if (list.getLegacyIssuesMaterial() != null) {
                    legacyIssuesBo.setLegacyIssuesMaterial(list.getLegacyIssuesMaterial());
                }
                if (list.getLegacyIssuesNumber() != null) {
                    legacyIssuesBo.setLegacyIssuesNumber(list.getLegacyIssuesNumber());
                }
                iTbLegacyIssuesService.insertByBo(legacyIssuesBo);

            }
        }
        return R.ok();
    }

    @Autowired
    private TbWheelDiameterMapper tbWheelDiameterMapper;

    //Json表单回填
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateJsonData")
    @Log(title = "Json表单回填", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/updateJsonData")
    public R<?> updateJsonData(@Validated(EditGroup.class) @RequestBody TbLmtrepairWorkdetailBo bo) {
        firstFillData(bo);
        modifyFillData(bo, "inspect_user");
        if ("2".equals(bo.getJsonStatus()) && bo.getFormConfig().contains("wheelDiameter")) {
            List<WheelDiameterDataVo> wheelDiameterDataList = iTbLmtrepairWorkdetailService.getWheelDiameterDataList(bo.getFillData());
            if (wheelDiameterDataList != null && wheelDiameterDataList.size() > 0 ) {
                TbWheelDiameter tbWheelDiameter = new TbWheelDiameter();
                tbWheelDiameter.setLmtrepairWorkdetailId(bo.getId());
                TbRepairplanlistVo tbRepairplanlistVo = iTbRepairplanlistService.queryById(bo.getLmtRepairId());
                if (tbRepairplanlistVo != null) {
                    tbWheelDiameter.setLmtNumber(tbRepairplanlistVo.getLmtNumber());
                    tbWheelDiameter.setLmtType(tbRepairplanlistVo.getLmtType());
                }

                tbWheelDiameter.setEndTime(new Date());
                tbWheelDiameter.setJsonData(JsonUtils.toJsonString(wheelDiameterDataList));
                tbWheelDiameterMapper.insert(tbWheelDiameter);
            }
        }
        return R.ok(iTbLmtrepairWorkdetailService.updateByBo(bo));
    }

    //查看表单数据内容，填充数据
    private void firstFillData(TbLmtrepairWorkdetailBo bo) {
        TbLmtrepairWorkdetailVo vo = iTbLmtrepairWorkdetailService.selectWorkInfo(bo.getId());
        String fillData = bo.getFillData();
        if (fillData != null && !fillData.isEmpty() && !fillData.equals("0")) {
            // 将 fillData 转换成 JSON 对象
            JSONObject jsonObject = JSON.parseObject(fillData);
            // 检查是否包含需要修改的字段
            if (jsonObject.containsKey("work_user")) {
                // 修改对应字段的值为当前用户的用户名
                jsonObject.put("work_user", LoginHelper.getLoginUser().getUsername());
                // 更新 TbLmtrepairWorkdetailBo 对象的 fillData 字段

            }
            if (jsonObject.containsKey("lmtNumber")) {
                // 修改对应字段的值为当前用户的用户名
                jsonObject.put("lmtNumber", vo.getLmtNumber());
                // 更新 TbLmtrepairWorkdetailBo 对象的 fillData 字段

            }
            if (jsonObject.containsKey("lmt_type")) {
                // 修改对应字段的值为当前用户的用户名
                jsonObject.put("lmt_type", vo.getLmtType());
                // 更新 TbLmtrepairWorkdetailBo 对象的 fillData 字段

            }
            if (jsonObject.containsKey("date")) {
                // 修改对应字段的值为当前用户的用户名
                jsonObject.put("date", new Date());
                // 更新 TbLmtrepairWorkdetailBo 对象的 fillData 字段

            }
            bo.setFillData(jsonObject.toJSONString());
        }
    }

    //todo 遗留问题
    //遗留问题右侧的显示列表
    @GetMapping("/list/workLegacy")
    public TableDataInfo<TbLegacyIssuesVo> workLegacyList(String id, String workSelect, String lmtType, String lmtNumber, String repairChar, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectWorkLegacyList(id, workSelect, lmtType, lmtNumber, repairChar, pageQuery);
    }

    //过程检查右侧的显示列表
    @GetMapping("/list/workCheck")
    public TableDataInfo<TbLmtrepairWorkdetailVo> workCheckList(String id, String workSelect, String lmtType, String lmtNumber, String repairChar, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectWorkCheckList(id, workSelect, lmtType, lmtNumber, repairChar, pageQuery);
    }

    //过程检查中的验收通过
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateAllowCheck")
    @Log(title = "检修任务中的任务完成", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/AllowCheck")
    public R<?> updateAllowCheckByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            bo.setStatus("已验收");
            LoginUser currentUser = LoginHelper.getLoginUser();
            bo.setCheckUser(currentUser.getUsername());
            bo.setCheckTime(new Date());
            //modifyFillData(bo);
            modifyFillData(bo, "examine_user");
            iTbLmtrepairWorkdetailService.updateByBo(bo);


//            //更新计划明细表锻检人
//            TbRepairplanlistBo rplBo = new TbRepairplanlistBo();
//            rplBo.setId(bo.getLmtRepairId());
//            rplBo.setCheckUser2(currentUser.getUsername());
//            rplBo.setCheckTime2(new Date());
//            iTbRepairplanlistService.updateByBo(rplBo);

            //更新质量验收表
            TbLmtrepairCheckdetailBo old = iTbLmtrepairCheckdetailService.selectByLmtId(bo.getId());
            if (old != null) {
                old.setWorkResult("已整改");
                old.setCheckTime(new Date());
                old.setCheckUser(currentUser.getUsername());
                old.setUpdateBy(currentUser.getUsername());
                old.setUpdateTime(new Date());
                old.setFinishTime(new Date());
                old.setWorkGroup(bo.getWorkGroup());
                old.setWorkUser(bo.getWorkUser());
                if (bo.getWorkUser2() != null && !bo.getWorkUser2().isEmpty()) {
                    old.setWorkUser2(bo.getWorkUser2());
                }
                iTbLmtrepairCheckdetailService.updateByBo(old);
            }
        }
        Long lmtId = bos.get(0).getLmtRepairId();
        String workType = bos.get(0).getWorkType();
        String lmtRepairId = String.valueOf(lmtId);
        if (iTbLmtrepairWorkdetailService.isFinishByLmtId(lmtRepairId)) {
            TbRepairplanlistBo rplBo = new TbRepairplanlistBo();
            rplBo.setId(lmtId);
//            if (workType.equals("二级修")){
//                rplBo.setStatus("已完成");
//            }
//            else{rplBo.setStatus("检修完成");}

            iTbRepairplanlistService.updateByBo(rplBo);
        }
        return R.ok();
    }

    //查看表单数据内容，填充审核人数据
    //private void modifyFillData(TbLmtrepairWorkdetailBo bo) {
    private void modifyFillData(TbLmtrepairWorkdetailBo bo, String name) {
        String fillData = bo.getFillData();
        if (fillData != null && !fillData.isEmpty() && !fillData.equals("0")) {
            // 将 fillData 转换成 JSON 对象
            JSONObject jsonObject = JSON.parseObject(fillData);
            // 检查是否包含需要修改的字段
            if (jsonObject.containsKey(name)) {
                // 修改对应字段的值为当前用户的用户名
                jsonObject.put(name, LoginHelper.getLoginUser().getUsername());
                // 更新 TbLmtrepairWorkdetailBo 对象的 fillData 字段
                bo.setFillData(jsonObject.toJSONString());
            }
        }
    }


    //过程检查中的返工
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateReturnCheck")
    @Log(title = "检修任务中的任务返工", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/ReturnCheck")
    public R<?> updateReturnCheckByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            bo.setStatus("未完成");
            //bo.setFillData(null);设置JsonStatus为1，草稿状态
            bo.setJsonStatus("1");
            if (bo.getRemark() != null) {
                bo.setRemark(bo.getRemark() + "[返工]");
            } else {
                bo.setRemark("[返工]");
            }
            iTbLmtrepairWorkdetailService.updateByBo(bo);
        }
        return R.ok();
    }

    //过程验收右侧的显示列表
    @GetMapping("/list/workApproval")
    public TableDataInfo<TbLmtrepairWorkdetailVo> workApprovalList(String id, String workSelect, String lmtType, String lmtNumber, String repairChar, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectWorkApprovalList(id, workSelect, lmtType, lmtNumber, repairChar, pageQuery);
    }


    //过程验收中的质检组必检通过
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateGroupApproval")
    @Log(title = "过程验收中的质检组必检通过", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/GroupApproval")
    public R<?> updateGroupApprovalByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            LoginUser currentUser = LoginHelper.getLoginUser();
//            bo.setCheckUser2(currentUser.getUsername());
//            bo.setCheckTime2(new Date());
            sendFillData(bo);
            iTbLmtrepairWorkdetailService.updateByBo(bo);

            //更新质量验收表
            TbLmtrepairCheckdetailBo old = iTbLmtrepairCheckdetailService.selectByLmtId(bo.getId());
            if (old != null) {
                old.setWorkResult("已整改");
                old.setCheckTime(new Date());
                old.setCheckUser(currentUser.getUsername());
                old.setUpdateBy(currentUser.getUsername());
                old.setUpdateTime(new Date());
                old.setFinishTime(new Date());
                old.setWorkGroup(bo.getWorkGroup());
                old.setWorkUser(bo.getWorkUser());
                if (bo.getWorkUser2() != null && !bo.getWorkUser2().isEmpty()) {
                    old.setWorkUser2(bo.getWorkUser2());
                }
                iTbLmtrepairCheckdetailService.updateByBo(old);
            }
        }
        Long lmtId = bos.get(0).getLmtRepairId();
        String workType = bos.get(0).getWorkType();
        String lmtRepairId = String.valueOf(lmtId);
        if (iTbLmtrepairWorkdetailService.isFinishByLmtId(lmtRepairId)) {
            TbRepairplanlistBo rplBo = new TbRepairplanlistBo();
            rplBo.setId(lmtId);
//            if (workType.equals("二级修")){
//                rplBo.setStatus("已完成");
//            }
//            else{rplBo.setStatus("检修完成");}

            iTbRepairplanlistService.updateByBo(rplBo);
        }
        return R.ok();
    }

    //TODO 查看表单数据内容，填充质检人数据
    private void sendFillData(TbLmtrepairWorkdetailBo bo) {
        String fillData = bo.getFillData();
        if (fillData != null && !fillData.isEmpty() && !fillData.equals("0")) {
            // 将 fillData 转换成 JSON 对象
            JSONObject jsonObject = JSON.parseObject(fillData);
            // 检查是否包含需要修改的字段
            if (jsonObject.containsKey("work_user3")) {
                // 修改对应字段的值为当前用户的用户名
                jsonObject.put("work_user3", LoginHelper.getLoginUser().getUsername());
                // 更新 TbLmtrepairWorkdetailBo 对象的 fillData 字段
                bo.setFillData(jsonObject.toJSONString());
            }
        }
    }


    //过程验收中的局必检通过
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateBureauApproval")
    @Log(title = "过程验收中的局必检通过", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/BureauApproval")
    public R<?> updateBureauApprovalByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            LoginUser currentUser = LoginHelper.getLoginUser();
            bo.setCheckUser3(currentUser.getUsername());
            bo.setCheckTime3(new Date());
            modifyFillData(bo, "check_accept_user");
            iTbLmtrepairWorkdetailService.updateByBo(bo);
            modifyFillData(bo, "check_accept_user");

            //更新质量验收表
            TbLmtrepairCheckdetailBo old = iTbLmtrepairCheckdetailService.selectByLmtId(bo.getId());
            if (old != null) {
                old.setWorkResult("已整改");
                old.setCheckTime(new Date());
                old.setCheckUser(currentUser.getUsername());
                old.setUpdateBy(currentUser.getUsername());
                old.setUpdateTime(new Date());
                old.setFinishTime(new Date());
                old.setWorkGroup(bo.getWorkGroup());
                old.setWorkUser(bo.getWorkUser());
                if (bo.getWorkUser2() != null && !bo.getWorkUser2().isEmpty()) {
                    old.setWorkUser2(bo.getWorkUser2());
                }
                iTbLmtrepairCheckdetailService.updateByBo(old);
            }
        }
        Long lmtId = bos.get(0).getLmtRepairId();
        String workType = bos.get(0).getWorkType();
        String lmtRepairId = String.valueOf(lmtId);
        if (iTbLmtrepairWorkdetailService.isFinishByLmtId(lmtRepairId)) {
            TbRepairplanlistBo rplBo = new TbRepairplanlistBo();
            rplBo.setId(lmtId);
//            if (workType.equals("二级修")){
//                rplBo.setStatus("已完成");
//            }
//            else{rplBo.setStatus("检修完成");}

            iTbRepairplanlistService.updateByBo(rplBo);
        }
        return R.ok();
    }


    //过程验收中的质检组问题反馈
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateReturnGroupApproval")
    @Log(title = "过程验收中的问题反馈", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/ReturnGroupApproval")
    public R<?> updateReturnGroupApprovalByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            bo.setWorkType("过程验收问题(质检组)");
            bo.setStatus("未下达");
            //bo.setFillData(null);设置JsonStatus为1，草稿状态
            bo.setJsonStatus("1");
            iTbLmtrepairWorkdetailService.updateByBo(bo);
            //把质检问题添加到质量验收表中
            TbLmtrepairCheckdetailBo checkBo = new TbLmtrepairCheckdetailBo();
            LoginUser currentUser = LoginHelper.getLoginUser();
            checkBo.setLmtRepairId(bo.getLmtRepairId());
            checkBo.setLmtRepairWorkId(bo.getId());
            checkBo.setCheckKind("段验问题");
            checkBo.setCheckUser(currentUser.getUsername());
            checkBo.setCheckTime(new Date());
            checkBo.setWorkName(bo.getWorkName());
            checkBo.setWorkRequire(bo.getWorkRequire());
            checkBo.setWorkResult("待处理");
            checkBo.setStartRequireDate(bo.getStartRequireDate());
            checkBo.setWorkGroup(bo.getWorkGroup());
            checkBo.setWorkUser(bo.getWorkUser());
            if (bo.getWorkUser2() != null && !bo.getWorkUser2().isEmpty()) {
                checkBo.setWorkUser2(bo.getWorkUser2());
            }
            checkBo.setStatus("已派活");

            checkBo.setCreateBy(currentUser.getUsername());
            checkBo.setCreateTime(new Date());
            if (iTbLmtrepairCheckdetailService.isStayById(bo.getId())) {
                checkBo.setID(iTbLmtrepairCheckdetailService.selectIdByLmtWorkId(bo.getId()));
                iTbLmtrepairCheckdetailService.updateByBo(checkBo);
            } else {
                iTbLmtrepairCheckdetailService.insertByBo(checkBo);
            }
        }
        return R.ok();
    }

    //过程验收中的局检问题反馈
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:updateReturnBureauApproval")
    @Log(title = "过程验收中的局检问题反馈", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/update/ReturnBureauApproval")
    public R<?> updateReturnBureauApprovalByBos(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            bo.setWorkType("过程验收问题(局)");
            bo.setStatus("未下达");
            //bo.setFillData(null);设置JsonStatus为1，草稿状态
            bo.setJsonStatus("1");
            iTbLmtrepairWorkdetailService.updateByBo(bo);
            //把局检问题添加到质量验收表中
            TbLmtrepairCheckdetailBo checkBo = new TbLmtrepairCheckdetailBo();
            LoginUser currentUser = LoginHelper.getLoginUser();
            checkBo.setLmtRepairId(bo.getLmtRepairId());
            checkBo.setLmtRepairWorkId(bo.getId());
            checkBo.setCheckKind("局验问题");
            checkBo.setCheckUser(currentUser.getUsername());
            checkBo.setCheckTime(new Date());
            checkBo.setWorkName(bo.getWorkName());
            checkBo.setWorkRequire(bo.getWorkRequire());
            checkBo.setWorkResult("待处理");
            checkBo.setStartRequireDate(bo.getStartRequireDate());
            checkBo.setWorkGroup(bo.getWorkGroup());
            checkBo.setWorkUser(bo.getWorkUser());
            if (bo.getWorkUser2() != null && !bo.getWorkUser2().isEmpty()) {
                checkBo.setWorkUser2(bo.getWorkUser2());
            }
            checkBo.setStatus("已派活");

            checkBo.setCreateBy(currentUser.getUsername());
            checkBo.setCreateTime(new Date());
            if (iTbLmtrepairCheckdetailService.isStayById(bo.getId())) {
                checkBo.setID(iTbLmtrepairCheckdetailService.selectIdByLmtWorkId(bo.getId()));
                iTbLmtrepairCheckdetailService.updateByBo(checkBo);
            } else {
                iTbLmtrepairCheckdetailService.insertByBo(checkBo);
            }
        }
        return R.ok();
    }

    //大机履历工作明细
    @GetMapping("/list/workHistory")
    public TableDataInfo<TbLmtrepairWorkdetailVo> workHistoryList(String id, String workKind, String workGroup, String workSelect, String status, Date startTime, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectWorkHistoryList(id, workKind, workGroup, workSelect, status, startTime, pageQuery);
    }


    /**
     * 新增预检任务
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:addPreflight")
    @Log(title = "提报预检工作", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add/preflight")
    public R<Void> addPreflight(@RequestBody Map map) {
        try {

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //新增预检任务到工作明细表
            TbLmtrepairWorkdetailBo bo = new TbLmtrepairWorkdetailBo();
            String lmtRepairId = String.valueOf(map.get("lmtRepairId"));
            if (lmtRepairId == null) {
                throw new RuntimeException("请确认大机是否有检修计划任务");
            }
            bo.setLmtRepairId(Long.parseLong(lmtRepairId));
            bo.setWorkName((String) map.get("workName"));
            bo.setStartRequireDate(map.get("requireStartTime") == null ? null : formatter.parse((String) map.get("requireStartTime")));
            bo.setWorkCategory((String) map.get("workCategory"));
            bo.setWorkCategoryId(map.get("workCategoryId") == null ? null : Long.parseLong(map.get("workCategoryId").toString()));
            bo.setWorkKind((String) map.get("workKind"));
            bo.setWorkRequire((String) map.get("checkReapirReqire"));
            bo.setWorkUser((String) map.get("workUser"));
            bo.setWorkUser2((String) map.get("workUser2"));
            bo.setWorkType("预检");
            bo.setStatus("未下达");
            bo.setCreateTime(new Date());
            LoginUser currentUser = LoginHelper.getLoginUser();
            bo.setCreateBy(currentUser.getUsername());
            iTbLmtrepairWorkdetailService.insertByBo(bo);
            //修改预检表信息
            TbFdxdetailBo tbFdxdetailBo = new TbFdxdetailBo();
            tbFdxdetailBo.setID(Long.parseLong((String) map.get("id")));
            tbFdxdetailBo.setStatus("已提报");
            iTbFdxdetailService.updateByBo(tbFdxdetailBo);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    /**
     * 新增过程验收任务
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:addPreflightDetail")
    @Log(title = "提报过程验收工作", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add/preflightDetail")
    public R<Void> addPreflightDetail(@Validated(AddGroup.class) @RequestBody Map map) {
        try {

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //新增过程验收任务到工作明细表
            TbLmtrepairWorkdetailBo bo = new TbLmtrepairWorkdetailBo();
            String lmtRepairId = String.valueOf(map.get("lmtRepairId"));
            if (lmtRepairId == null) {
                throw new RuntimeException("请确认大机是否有检修计划任务");
            }
            bo.setLmtRepairId(Long.parseLong(lmtRepairId));
            bo.setWorkName((String) map.get("workName"));
            bo.setStartRequireDate(formatter.parse((String) map.get("requireStartTime")));
            bo.setWorkCategory((String) map.get("workCategory"));
            bo.setWorkCategoryId(map.get("workCategoryId") == null ? null : Long.parseLong(map.get("workCategoryId").toString()));
            bo.setWorkKind((String) map.get("workKind"));
            bo.setWorkRequire((String) map.get("checkReapirReqire"));
            bo.setWorkUser((String) map.get("workUser"));
            bo.setWorkUser2((String) map.get("workUser2"));
            bo.setWorkType("过程验收");
            bo.setStatus("未下达");
            bo.setCreateTime(new Date());
            LoginUser currentUser = LoginHelper.getLoginUser();
            Long workGroupId = LoginHelper.getDeptId();

            bo.setCreateBy(currentUser.getUsername());

            Long boId = iTbLmtrepairWorkdetailService.insertByBoReturnId(bo);
            //过程验收，新增通知消息
            TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
            TbLmtrepairWorkdetailVo list = iTbLmtrepairWorkdetailService.selectWorkInfo(boId);
            messageNoticeBo.setMessageId(boId);
            messageNoticeBo.setMessageTitle(list.getLmtNumber() + "添加了过程验收问题");
            messageNoticeBo.setMessageName(currentUser.getUsername() + "添加了" + list.getLmtNumber() + "大机的过程验收问题，请及时处理。");
            messageNoticeBo.setMessageType("过程验收问题");
            messageNoticeBo.setLmtType(list.getLmtType());
            messageNoticeBo.setLmtNumber(list.getLmtNumber());
            messageNoticeBo.setWorkGroup(currentUser.getDeptName());
            messageNoticeBo.setWorkUser(currentUser.getUsername());
            messageNoticeBo.setWorkerTeam(list.getWorkerTeam());
            messageNoticeBo.setStatus("0");
            messageNoticeBo.setWorkGroupId(workGroupId);
            messageNoticeBo.setTaskUrl(list.getTaskUrl());
            messageNoticeBo.setWorkTime(new Date());
            //设置通知人工队长
            messageNoticeBo.setRecipient(iTbMessageNoticeService.getCaptain(list.getWorkGroupId()));
            iTbMessageNoticeService.insertByBo(messageNoticeBo);

            //修改过程验收表信息
            TbPreflightdetailBo tbPreflightdetailBo = new TbPreflightdetailBo();
            String id = (String) map.get("id");
            tbPreflightdetailBo.setID(Long.valueOf(id));
            tbPreflightdetailBo.setStatus("已提报");
            iTbPreflightdetailService.updateByBo(tbPreflightdetailBo);


            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    //todo 5/9权限待修改

    /**
     * 新增临修任务
     */
    @Log(title = "临修工作", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add/temporary")
    public R<Void> addTemporary(@Validated(AddGroup.class) @RequestBody TbLmtrepairWorkdetailBo bo) {
        bo.setStatus("未提报");
        bo.setWorkType("临修");
        return toAjax(iTbLmtrepairWorkdetailService.insertByBo(bo));
    }

    //根据lmtRepairId查询指定工作详情
    @GetMapping("/list/selectTaskAllById")
    public TableDataInfo<TbLmtrepairWorkdetailVo> selectTaskAllById(String lmtRepairId, String lmtType, String lmtNumber, String status, String repairChar, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectTaskAllById(lmtRepairId, lmtType, lmtNumber, status, repairChar, pageQuery);
    }

    //根据lmtRepairId查询指定遗留问题工作详情
    @GetMapping("/list/selectLegacyById")
    public TableDataInfo<TbLmtrepairWorkdetailVo> selectLegacyById(String lmtRepairId, String lmtType, String lmtNumber, String status, String repairChar, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectLegacyById(lmtRepairId, lmtType, lmtNumber, status, repairChar, pageQuery);
    }

    /**
     * 新增互检任务
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:addMutual")
    @Log(title = "提报互检工作", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add/Mutual")
    public R<Void> addMutual(@Validated(AddGroup.class) @RequestBody List<Map> maps) {
        System.out.println(maps.size());

        try {
            //修改互检主表信息
            LoginUser loginUser = LoginHelper.getLoginUser();
            Long workGroupId = loginUser.getDeptId();
            String workUser = loginUser.getUsername();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //新增任务表内容
            for (Map map : maps) {
                TbLmtrepairWorkdetailBo bo = new TbLmtrepairWorkdetailBo();
                String lmtRepairId = String.valueOf(map.get("lmtRepairId"));
                if (lmtRepairId == null) {
                    throw new RuntimeException("请确认大机是否有检修计划任务");
                }
                bo.setLmtRepairId(Long.parseLong(lmtRepairId));
                bo.setWorkName((String) map.get("workName"));
                bo.setStartRequireDate(map.get("repairStartDate") == null ? null : formatter.parse((String) map.get("repairStartDate")));
                bo.setWorkCategory((String) map.get("workCategory"));
                bo.setWorkCategoryId(map.get("workCategoryId") == null ? null : Long.parseLong(map.get("workCategoryId").toString()));
                bo.setWorkKind((String) map.get("workKind"));
                bo.setWorkRequire((String) map.get("checkReapirReqire"));
                bo.setWorkUser((String) map.get("workUser"));
                bo.setWorkUser2((String) map.get("workUser2"));
                bo.setWorkType("互检");
                bo.setStatus("未下达");
                bo.setCreateTime(new Date());
                bo.setAcceptanceId(Long.parseLong((String) map.get("id")));
                LoginUser currentUser = LoginHelper.getLoginUser();
                bo.setCreateBy(currentUser.getUsername());
                iTbLmtrepairWorkdetailService.insertByBo(bo);
                //互检提报后修改计划状态
                TbRepairplanlistBo tbRepairplanlist = new TbRepairplanlistBo();
                tbRepairplanlist.setId(bo.getLmtRepairId());
                tbRepairplanlist.setStatus("检修中");
                TbRepairplanlistVo tbRepairplanlistVo = iTbRepairplanlistService.queryById(tbRepairplanlist.getId());
                iTbRepairplanlistService.updateByBo(tbRepairplanlist);
                if (tbRepairplanlistVo != null) {
                    TbRepairplanBo tbRepairplanBo = new TbRepairplanBo();
                    tbRepairplanBo.setId(tbRepairplanlistVo.getPlanId());
                    tbRepairplanBo.setStatus("正式计划");
                    boolean b = iTbRepairplanService.updateByBo(tbRepairplanBo);
                }
                //修改互检表信息
                TbMutualInspectiondetailBo tbMutualInspectiondetailBo = new TbMutualInspectiondetailBo();
                tbMutualInspectiondetailBo.setID(Long.parseLong((String) map.get("id")));
                tbMutualInspectiondetailBo.setStatus("已提报");
                tbMutualInspectiondetailBo.setWorkGroupId(workGroupId);
                tbMutualInspectiondetailBo.setWorkUser(workUser);
                iTbMutualInspectiondetailService.updateByBo(tbMutualInspectiondetailBo);
            }
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    //根据lmtRepairId查询互检工作详情
    @GetMapping("/list/selectMutualById")
    public TableDataInfo<TbLmtrepairWorkdetailVo> selectMutualById(String lmtRepairId, String lmtType, String lmtNumber, String status, String repairChar, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectMutualById(lmtRepairId, lmtType, lmtNumber, status, repairChar, pageQuery);
    }

    //根据lmtRepairId查询专检工作详情
    @GetMapping("/list/selectSpecialById")
    public TableDataInfo<TbLmtrepairWorkdetailVo> selectSpecialById(String lmtRepairId, String lmtType, String lmtNumber, String status, String repairChar, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectSpecialById(lmtRepairId, lmtType, lmtNumber, status, repairChar, pageQuery);
    }

    /**
     * 新增专检任务
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:addSpecial")
    @Log(title = "提报专检工作", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add/Special")
    public R<Void> addSpecial(@Validated(AddGroup.class) @RequestBody List<Map> maps) {

        try {
            //
            LoginUser loginUser = LoginHelper.getLoginUser();
            Long workGroupId = loginUser.getDeptId();
            String workUser = loginUser.getUsername();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //新增任务表信息
            for (Map map : maps) {
                TbLmtrepairWorkdetailBo bo = new TbLmtrepairWorkdetailBo();
                String lmtRepairId = String.valueOf(map.get("lmtRepairId"));
                if (lmtRepairId == null) {
                    throw new RuntimeException("请确认大机是否有检修计划任务");
                }
                bo.setLmtRepairId(Long.parseLong(lmtRepairId));
                bo.setWorkName((String) map.get("workName"));
                bo.setStartRequireDate(formatter.parse((String) map.get("repairStartDate")));
                bo.setWorkCategory((String) map.get("workCategory"));
                bo.setWorkCategoryId(map.get("workCategoryId") == null ? null : Long.parseLong(map.get("workCategoryId").toString()));
                bo.setWorkKind((String) map.get("workKind"));
                bo.setWorkRequire((String) map.get("checkReapirReqire"));
                bo.setWorkUser((String) map.get("workUser"));
                bo.setWorkUser2((String) map.get("workUser2"));
                bo.setWorkType("专检");
                bo.setStatus("未下达");
                bo.setAcceptanceId(Long.parseLong((String) map.get("id")));
                bo.setCreateTime(new Date());
                LoginUser currentUser = LoginHelper.getLoginUser();
                bo.setCreateBy(currentUser.getUsername());
                iTbLmtrepairWorkdetailService.insertByBo(bo);
                //专检提报后修改计划状态
                TbRepairplanlistBo tbRepairplanlist = new TbRepairplanlistBo();
                tbRepairplanlist.setId(bo.getLmtRepairId());
                tbRepairplanlist.setStatus("检修中");
                TbRepairplanlistVo tbRepairplanlistVo = iTbRepairplanlistService.queryById(tbRepairplanlist.getId());
                iTbRepairplanlistService.updateByBo(tbRepairplanlist);
                if (tbRepairplanlistVo != null) {
                    TbRepairplanBo tbRepairplanBo = new TbRepairplanBo();
                    tbRepairplanBo.setId(tbRepairplanlistVo.getPlanId());
                    tbRepairplanBo.setStatus("正式计划");
                    iTbRepairplanService.updateByBo(tbRepairplanBo);
                }
                //修改专检表信息

                TbSpecialInspectiondetailBo tbSpecialBo = new TbSpecialInspectiondetailBo();
                tbSpecialBo.setID(Long.parseLong((String) map.get("id")));
                tbSpecialBo.setStatus("已提报");
                tbSpecialBo.setWorkGroupId(workGroupId);
                tbSpecialBo.setWorkUser(workUser);
                iTbSpecialInspectiondetailService.updateByBo(tbSpecialBo);
            }
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    //根据lmtRepairId查询验收工作详情
    @GetMapping("/list/selectAcceptanceById")
    public TableDataInfo<TbLmtrepairWorkdetailVo> selectAcceptanceById(String lmtRepairId, String lmtType, String lmtNumber, String status, String repairChar, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectAcceptanceById(lmtRepairId, lmtType, lmtNumber, status, repairChar, pageQuery);
    }

    /**
     * 新增验收任务
     */
    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:addAcceptance")
    @Log(title = "提报验收工作", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add/Acceptance")
    public R<Void> addAcceptance(@Validated(AddGroup.class) @RequestBody List<Map> maps) {
        try {
            //修改验收主表信息
            LoginUser loginUser = LoginHelper.getLoginUser();
            Long workGroupId = loginUser.getDeptId();
            String workUser = loginUser.getUsername();
            for (Map map : maps) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                TbAcceptancedetailBo tbAcceptBo = new TbAcceptancedetailBo();
                tbAcceptBo.setID(Long.parseLong((String) map.get("id")));
                tbAcceptBo.setStatus("已提报");
                tbAcceptBo.setWorkUser(workUser);
                tbAcceptBo.setWorkGroupId(workGroupId);
                iTbAcceptancedetailService.updateByBo(tbAcceptBo);
                //新增验收任务到任务表中
                TbLmtrepairWorkdetailBo bo = new TbLmtrepairWorkdetailBo();
                String lmtRepairId = String.valueOf(map.get("lmtRepairId"));
                if (lmtRepairId == null) {
                    throw new RuntimeException("请确认大机是否有检修计划任务");
                }
                bo.setLmtRepairId(Long.parseLong(lmtRepairId));
                bo.setWorkName((String) map.get("workName"));
                bo.setStartRequireDate(map.get("repairStartDate") == null ? null : formatter.parse((String) map.get("repairStartDate")));
                bo.setWorkGroup((String) map.get("workCategory"));
                bo.setWorkCategoryId(map.get("workCategoryId") == null ? null : Long.parseLong(map.get("workCategoryId").toString()));
                bo.setWorkKind((String) map.get("workKind"));
                bo.setWorkRequire((String) map.get("checkReapirReqire"));
                bo.setWorkGroup((String) map.get("workCategory"));
                bo.setWorkUser((String) map.get("workUser"));
                bo.setWorkUser2((String) map.get("workUser2"));
                bo.setWorkType("验收");
                bo.setStatus("未下达");
                bo.setAcceptanceId(Long.parseLong((String) map.get("id")));
                bo.setCreateTime(new Date());
                LoginUser currentUser = LoginHelper.getLoginUser();
                bo.setCreateBy(currentUser.getUsername());

                iTbLmtrepairWorkdetailService.insertByBo(bo);
                //专检提报后修改计划状态
                TbRepairplanlistBo tbRepairplanlist = new TbRepairplanlistBo();
                tbRepairplanlist.setId(bo.getLmtRepairId());
                tbRepairplanlist.setStatus("检修中");
                TbRepairplanlistVo tbRepairplanlistVo = iTbRepairplanlistService.queryById(tbRepairplanlist.getId());
                iTbRepairplanlistService.updateByBo(tbRepairplanlist);
                TbRepairplanBo tbRepairplanBo = new TbRepairplanBo();
                tbRepairplanBo.setId(tbRepairplanlistVo.getPlanId());
                tbRepairplanBo.setStatus("正式计划");
                iTbRepairplanService.updateByBo(tbRepairplanBo);
            }
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    //首页当日任务

    @GetMapping("/list/indexTest")
    public TableDataInfo<TbLmtrepairWorkdetailVo> indexTest(String lmtType, String lmtNumber, String workType, String workGroup, String startTime, String endTime, PageQuery pageQuery) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return iTbLmtrepairWorkdetailService.selectIndexTest(lmtType, lmtNumber, workType, workGroup, StringUtils.isBlank(startTime) ? null : formatter.parse(startTime), StringUtils.isBlank(endTime) ? null : formatter.parse(endTime), pageQuery);
    }

    @PostMapping("/list/indexTest/export")
    public void indexTestExport(String lmtType, String lmtNumber, String workType, String workGroup, String startTime, String endTime, HttpServletResponse response) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<TbLmtrepairWorkdetailVo> tbLmtrepairWorkdetailVos =
            iTbLmtrepairWorkdetailService.selectIndexTestExport(lmtType, lmtNumber, workType, workGroup,
                StringUtils.isBlank(startTime) ? null : formatter.parse(startTime), StringUtils.isBlank(endTime) ? null : formatter.parse(endTime));
        ExcelUtil.exportExcel(tbLmtrepairWorkdetailVos, "首页当日任务", TbLmtrepairWorkdetailVo.class, response);
    }

    //首页当日未完成任务
    @GetMapping("/list/indexNotTest")
    public TableDataInfo<TbLmtrepairWorkdetailVo> indexNotTest(String lmtType, String lmtNumber, String workType, String workGroup, String startTime, String endTime, PageQuery pageQuery) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return iTbLmtrepairWorkdetailService.selectIndexNotTest(lmtType, lmtNumber, workType, workGroup,
            StringUtils.isBlank(startTime) ? null : formatter.parse(startTime), StringUtils.isBlank(endTime) ? null : formatter.parse(endTime), pageQuery);
    }

    @PostMapping("/list/indexNotTest/export")
    public void indexNotTestexport(String lmtType, String lmtNumber, String workType, String workGroup, String startTime, String endTime, HttpServletResponse response) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<TbLmtrepairWorkdetailVo> tbLmtrepairWorkdetailVos = iTbLmtrepairWorkdetailService.selectIndexNotTestExport(lmtType, lmtNumber, workType,
            workGroup, StringUtils.isBlank(startTime) ? null : formatter.parse(startTime), StringUtils.isBlank(endTime) ? null : formatter.parse(endTime));
        ExcelUtil.exportExcel(tbLmtrepairWorkdetailVos, "首页当日未完成任务", TbLmtrepairWorkdetailVo.class, response);
    }

    //返回消息通知任务数

    @GetMapping("/list/selectMessage")
    public MessageTestVo selectMessage() {
        return iTbLmtrepairWorkdetailService.selectMessage();
    }


    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:approvalIssues")
    @Log(title = "遗留问题审批通过", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/approvalIssues")
    public R<?> approvalIssues(@Validated(EditGroup.class) @RequestBody List<TbLmtrepairWorkdetailBo> bos) {
        for (TbLmtrepairWorkdetailBo bo : bos) {
            bo.setLegacyIssuesStatus(1);
            iTbLmtrepairWorkdetailService.updateByBo(bo);
        }
        return R.ok();
    }

    @SaCheckPermission("xha-lmt:lmtrepairWorkdetail:refuseIssues")
    @Log(title = "遗留问题审批拒绝", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/refuseIssues")
    public R<?> refuseIssues(@Validated(EditGroup.class) @RequestBody TbLmtrepairWorkdetailBo bo) {
        //添加到消息通知表中，
        //根据id查询通知表中原来的申请遗留信息
        TbMessageNoticeVo Message = null;
        try {
            Message = iTbMessageNoticeService.selectById(bo.getId());
        } catch (Exception e) {
            // 现在抛出一个新的RuntimeException
            throw new RuntimeException("已驳回");
        }
        //根据原来的申请遗留，新增通知消息
        TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
        TbLmtrepairWorkdetailVo list = iTbLmtrepairWorkdetailService.selectWorkInfo(bo.getId());
        messageNoticeBo.setMessageId(bo.getId());
        messageNoticeBo.setMessageTitle(list.getLmtNumber() + "任务申请遗留拒绝");
        messageNoticeBo.setMessageName(Message.getRecipient() + "拒绝了" + list.getLmtNumber() + "大机的任务遗留申请，请及时处理。");
        messageNoticeBo.setMessageType("遗留申请");
        messageNoticeBo.setLmtType(list.getLmtType());
        messageNoticeBo.setLmtNumber(list.getLmtNumber());
        messageNoticeBo.setWorkGroup(list.getWorkGroup());
        messageNoticeBo.setWorkUser(Message.getMessageNeed());
        messageNoticeBo.setWorkerTeam(list.getWorkerTeam());
        messageNoticeBo.setStatus("0");
        messageNoticeBo.setWorkGroupId(Message.getWorkGroupId());
        messageNoticeBo.setTaskUrl(list.getTaskUrl());
        messageNoticeBo.setWorkTime(new Date());
        //设置接收人为申请人
        messageNoticeBo.setRecipient(Message.getWorkUser());
        iTbMessageNoticeService.insertByBo(messageNoticeBo);

        bo.setStatus("未派活");
        bo.setLegacyIssuesStatus(2);
        bo.setLegacyIssues("");
        bo.setLegacyIssuesData("");
        bo.setLegacyIssuesMaterial("");
        bo.setLegacyIssuesRemark("");
        bo.setLegacyIssuesSolution("");
        bo.setLegacyIssuesNumber("");
        iTbLmtrepairWorkdetailService.updateByBo(bo);
        return R.ok();
    }

    //大机履历信息
    @GetMapping("/historyDetail")
    public HistoryDetailVo historyDetail(Long lmtRepairId) {
        return iTbLmtrepairWorkdetailService.selectHistoryDetailList(lmtRepairId);
    }

    @GetMapping("/historyDetail2")
    public R<JSONArray> historyDetail2(Long lmtRepairId) {
        return R.ok(iTbLmtrepairWorkdetailService.historyDetail2(lmtRepairId));
    }

    //通过id查询任务详情
    @GetMapping("/selectWorkInfo")
    public TbLmtrepairWorkdetailVo selectWorkInfo(Long id) {
        return iTbLmtrepairWorkdetailService.selectWorkInfo(id);
    }

    //首页当日任务完成度的折线图
    @GetMapping("/getTaskStats")
    public List<TaskStatsVo> getTaskStats(String startDate, String endDate) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date utilStartDate = sdf.parse(startDate);  // 解析为 java.util.Date 对象

        Date utilEndDate = sdf.parse(endDate);  // 解析为 java.util.Date 对象

        return iTbLmtrepairWorkdetailService.getTaskStats(utilStartDate, utilEndDate);
    }

    //获取任务下达中已下达未下达任务的数量
    @GetMapping("/selectTestCount")
    public MyTestCountVO selectTestCount(String id) {
        return iTbLmtrepairWorkdetailService.selectTestCount(id);
    }


    //检修任务中的任务数
    @GetMapping("/selectAcceptCountById")
    public AcceptCountVo selectAcceptCountById(String id, String workSelect) {
        return iTbLmtrepairWorkdetailService.selectAcceptCountById(id, workSelect);
    }

    /**
     * 移动端接口
     */

    //我的任务计数
    @GetMapping("/selectMyTestVo")
    public MyTestCountVO selectWorkList() {
        return iTbLmtrepairWorkdetailService.selectMyTestVo();
    }

    //遗留任务详情
    @GetMapping("/selectUserIssuesWorkList")
    public TableDataInfo<TbLegacyIssuesVo> selectUserIssuesWorkList(String lmtType, String lmtNumber, String workType, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectUserIssuesWorkList(lmtType, lmtNumber, workType, pageQuery);
    }

    //当日未完成任务详情
    @GetMapping("/selectIssuesWorkList")
    public TableDataInfo<TbLmtrepairWorkdetailVo> selectIssuesWorkList(String lmtType, String lmtNumber, String workType, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectIssuesWorkList(lmtType, lmtNumber, workType, pageQuery);
    }


    //已提交提料列表
    @GetMapping("/selectPickupList")
    public TableDataInfo<TbLmtrepairWorkdetailVo> selectPickupList(PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectPickupList(pageQuery);
    }


    //我要验收计数  AcceptCountVo

    @GetMapping("/selectAcceptCount")
    public AcceptCountVo selectAcceptCount() {
        return iTbLmtrepairWorkdetailService.selectAcceptCount();
    }

    @GetMapping("/selectAcceptList")
    public TableDataInfo<TbLmtrepairWorkdetailVo> selectAcceptList(String status, PageQuery pageQuery) {
        return iTbLmtrepairWorkdetailService.selectAcceptList(status, pageQuery);
    }

    /**
     * 获取部门列表
     */
    @GetMapping("/selectDeptList")
    public List<DeptVo> selectDeptTree() {
        return iTbLmtrepairWorkdetailService.selectDeptVoList();
    }

    /**
     * 获取部门列表人员信息
     */
    @GetMapping("/selectUserList")
    public List<DeptVo> selectUserList(Long deptId) {
        return iTbLmtrepairWorkdetailService.selectUserList(deptId);
    }
}
